/**
 * 
 */
package com.thon.security;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.thon.commons.utils.ApplicationEnum.UserStatus;
import com.thon.commons.utils.Encodes;
import com.thon.entity.system.Roles;
import com.thon.entity.system.RolesAuthority;
import com.thon.entity.system.Users;
import com.thon.entity.user.User;
import com.thon.service.system.RolesAuthorityService;
import com.thon.service.user.UserService;
import com.thon.service.user.impl.UserServiceImpl;

/**
 * @file ShiroDbRealm.java
 * @author manpiaoyi
 * @email manpiaoyi@126.com
 * @date 2014-10-13
 * @description:
 */

public class ShiroDbRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	@Autowired
	private RolesAuthorityService rolesAuthorityService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		User user = userService.getUser(token.getUsername(), UserStatus.open.getCode());
		if(user==null)
			user = userService.getUserByName(token.getUsername(), UserStatus.open.getCode());
		if (user != null) {
			SecurityUtils.getSubject().getSession().setTimeout(-1000L);
			String authcType = token.getAuthcType();
			String captcha = token.getCaptcha();
			String exitCode = (String) SecurityUtils.getSubject().getSession().getAttribute(CaptchaServlet.KEY_CAPTCHA);
			
			if (authcType.equalsIgnoreCase(AuthcType.BASIC)) {
				// basic认证使用plain text校验器
				HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserServiceImpl.HASH_ALGORITHM);
				matcher.setHashIterations(UserServiceImpl.HASH_INTERATIONS);
				setCredentialsMatcher(matcher);
				byte[] salt = Encodes.decodeHex(user.getSalt());
				return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName(), user.getAvatarUrl(), user.getFirstName(), user.getLastName(), user.getRoles()),
						user.getPassword(), ByteSource.Util.bytes(salt), getName());
				
			}else if(authcType.equalsIgnoreCase(AuthcType.FORM)){
				if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) {
					throw new CaptchaException();
				}				
				// 定Password校验的Hash算法与迭代次数.
				HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserServiceImpl.HASH_ALGORITHM);
				matcher.setHashIterations(UserServiceImpl.HASH_INTERATIONS);
				setCredentialsMatcher(matcher);
				byte[] salt = Encodes.decodeHex(user.getSalt());
				return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName(), user.getAvatarUrl(), user.getFirstName(), user.getLastName(), user.getRoles()),
						user.getPassword(), ByteSource.Util.bytes(salt), getName());
			}
			else if(authcType.equalsIgnoreCase(AuthcType.REGIST)){
							
				// 定Password校验的Hash算法与迭代次数.
				HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserServiceImpl.HASH_ALGORITHM);
				matcher.setHashIterations(UserServiceImpl.HASH_INTERATIONS);
				setCredentialsMatcher(matcher);
				byte[] salt = Encodes.decodeHex(user.getSalt());
				return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName(), user.getAvatarUrl(), user.getFirstName(), user.getLastName(), user.getRoles()),
						user.getPassword(), ByteSource.Util.bytes(salt), getName());
			}
			else if(authcType.equalsIgnoreCase(AuthcType.SOCIAL)){
				// basic认证使用plain text校验器
				SimpleCredentialsMatcher matcher = new SimpleCredentialsMatcher();
				setCredentialsMatcher(matcher);
				
				return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName(), user.getAvatarUrl(), user.getFirstName(), user.getLastName(), user.getRoles()),
						"", getName());
			}else {
				throw new UnknownAccountException();
			}
			
		} else {
			user = userService.getUser(token.getUsername(), UserStatus.locked.getCode());
			if (user != null) {
				throw new LockedAccountException();
			}else {
				throw new UnknownAccountException();
			}
		}
	}
	
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		User user = userService.getUser(shiroUser.loginName, UserStatus.open.getCode());
		userService.updateUserLoginInfo(user.getId());
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole(user.getRoles().getRoleCode());
		List<RolesAuthority> rolesAuthorityList = rolesAuthorityService.getRolesAuthority("roleType.id", user.getRoles().getRoleType().getId());
		Collection<String> permissions = new HashSet<String>();
		for(RolesAuthority rolesAuthority:rolesAuthorityList){
			permissions.add(rolesAuthority.getAuthority().getModule().getDicDataCode()+":"+rolesAuthority.getAuthority().getpermissions().getDicDataCode());
		}
		info.addStringPermissions(permissions);
		return info; 
	} 
	
	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public Integer id;
		public String loginName;
		public String name;
		public String avatarUrl;
		public String fullName;
		public Roles roles;

		public ShiroUser(Integer id, String loginName, String name, String avatarUrl, String firstName, String lastName, Roles roles) {
			this.id = id;
			this.loginName = loginName;
			this.name = name;
			this.avatarUrl = avatarUrl;
			this.fullName = firstName + " " + lastName;
			this.roles = roles;
		}
		
		public Integer getId() {
			return id;
		}
		
		public String getLoginName() {
			return loginName;
		}

		public String getName() {
			return name;
		}
		
		public String getFullName() {
			return fullName;
		}
		
		public Roles getRoles() {
			return roles;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return loginName;
		}

		public String getAvatarUrl() {
			return avatarUrl;
		}

		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return HashCodeBuilder.reflectionHashCode(this, "loginName");
		}

		/**
		 * 重载equals,只比较loginName
		 */
		@Override
		public boolean equals(Object obj) {
			return EqualsBuilder.reflectionEquals(this, obj, "loginName");
		}
	}

}
